package com.xoms.front.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xoms.front.aspect.datasource.DataSourceSwitcher;
import com.xoms.front.cache.dao.ProCategoryCache;
import com.xoms.front.controller.res.bean.RAllProductsBean;
import com.xoms.front.controller.res.bean.RProductBean;
import com.xoms.front.model.AccountBean;
import com.xoms.front.model.ProductBean;
import com.xoms.front.model.StoreHouseBean;
import com.xoms.front.model.vo.ProCategoryVo;
import com.xoms.front.persist.dao.ProCategoryDao;
import com.xoms.front.persist.dao.ProductDao;
import com.xoms.front.persist.dao.StoreHouseDao;
import com.xoms.front.service.ProductService;
import com.xoms.front.service.exception.ServiceException;
import com.xoms.front.service.res.PageResult;
import com.xoms.util.DateTimeUtil;

@Service
public class ProductServiceImpl implements ProductService {

	Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	ProCategoryCache proCategoryCacheImpl;

	@Autowired
	ProductDao productImpl;

	@Autowired
	ProCategoryDao proCategoryImpl;

	@Autowired
	StoreHouseDao storeHouseImpl;

	@Override
	public PageResult<RAllProductsBean> geAllProducts(AccountBean account, int page, int pageSize) {
		PageResult<RAllProductsBean> result = new PageResult<RAllProductsBean>();

		// 切换至总部数据源
		DataSourceSwitcher.setDataSourceType(DataSourceSwitcher.DATA_SOURCE_HQ);
		// 总部二级分类
		List<ProCategoryVo> hqCates2 = proCategoryImpl.selectHqSecondCates();

		// 切换至影院数据源
		DataSourceSwitcher.setDataSourceType(DataSourceSwitcher.DATA_SOURCE_XOMS);
		StoreHouseBean storeHouse = storeHouseImpl.selectOneByAdminIdAndType(account.getAccid(), 2);
		if (storeHouse == null) {
			throw new ServiceException("object_is_not_exist", "当前账户关联柜台");
		}
		String sid = storeHouse.getSid();
		// 影院分类
		List<ProCategoryVo> cate3s = proCategoryImpl.selectAllCates();
		// 查询分类下所有商品列表
		List<ProductBean> lists = productImpl.selectListByStoreHouseId(null, false, page, pageSize, null, null, sid, 1);

		if (cate3s == null) {
			return null;
		}
		if (hqCates2 == null) {
			return null;
		}

		// 三级分类根据parentId分组排序 key 二级id value 三级分类list
		Map<String, List<ProCategoryVo>> map = cate3s.stream().filter(o -> Objects.nonNull(o.getParentId()))
				.collect(Collectors.groupingBy(ProCategoryVo::getParentId));
		
		List<ProCategoryVo> cates3sort = new ArrayList<>();

		for (ProCategoryVo vo : hqCates2) {
			if (map.containsKey(vo.getCid())) {
				cates3sort.addAll(map.get(vo.getCid()));
			} 
		}

		// 商品分类
		Map<String, List<ProductBean>> categoryProMap = lists.stream().filter(o -> Objects.nonNull(o.getCategoryId()))
				.collect(Collectors.groupingBy(ProductBean::getCategoryId));

		List<RAllProductsBean> resList = new ArrayList<RAllProductsBean>();
		for (ProCategoryVo vo : cates3sort) {
			if (categoryProMap.containsKey(vo.getCid())) {
				List<ProductBean> lis = categoryProMap.get(vo.getCid());
				List<RProductBean> proList = parseProList(lis);
				RAllProductsBean rb = new RAllProductsBean();
				rb.setCid(vo.getCid());
				rb.setLevel(vo.getLevel());
				rb.setName(vo.getName());
				rb.setParentId(vo.getParentId());
				rb.setProList(proList);
				resList.add(rb);
			} else {// 没有商品处理
				RAllProductsBean rb = new RAllProductsBean();
				rb.setCid(vo.getCid());
				rb.setLevel(vo.getLevel());
				rb.setName(vo.getName());
				rb.setParentId(vo.getParentId());
				rb.setProList(null);
				resList.add(rb);
			}
		}
		result.setData(resList);
		result.setCount(resList.size());
		return result;
	}

	private List<RProductBean> parseProList(List<ProductBean> list) {
		List<RProductBean> res = new ArrayList<>();
		if (list != null && list.size() > 0) {
			list.forEach(pro -> {
				res.add(parse(pro));
			});
		}
		return res;
	}

	/**
	 * 格式化商品数据
	 * 
	 * @param acc
	 * @return
	 */
	private RProductBean parse(ProductBean pro) {
		RProductBean res = new RProductBean();
		res.setAccount(pro.getAccountId());
		res.setPid(pro.getPid());
		res.setName(pro.getName());
		res.setCategory(pro.getCategory());
		res.setImgUrl(pro.getImgUrl());
		res.setSpecs(pro.getSpecs());
		res.setUnit(pro.getUnit());
		res.setProductBar(pro.getProductBar());
		res.setProductNo(pro.getProductNo());
		res.setRemark(pro.getRemark());
		res.setAccount(pro.getAccount());
		res.setPrice(pro.getPrice());
		res.setUnitId(pro.getUnitId() + "");
		res.setCategoryArr(pro.getCategoryArr());
		res.setSaleStatus(pro.getSaleStatus());
		res.setStartTime(DateTimeUtil.formatTimestamp(pro.getStartTime()));
		res.setEndTime(DateTimeUtil.formatTimestamp(pro.getEndTime()));
		res.setCreateTime(DateTimeUtil.formatTimestamp(pro.getCreateTime()));
		res.setNumber(pro.getNumber());
		res.setStore(pro.getStore());
		return res;
	}

}
